﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using 新门禁;
using 新门禁.Utils;
using SmartWeighMonitor;
using System.Runtime.InteropServices;
using System.Windows.Controls;
using System.Reflection.Emit;


namespace GuardMonitor.Utils
{
    public class HttpServer
    {
        public static event MMSendMsg sendMsgEvent;
        public static event MMSendMsg sendVideoEvent;
        private int port = 9000;
        private HttpListener httpListener;
        private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB = null;
        public  int handleIN;
        public int handleOUT;
        string yy;

        public HttpServer()
        {
            this.httpListener = new HttpListener();
        }
        public HttpServer(int port) : this()
        {
            this.port = port;
        }


        public const uint LED_COLOR_RED = 0x000000FF; //红色
        public const uint LED_COLOR_GREEN = 0x0000FF00; //绿色
        public const uint LED_COLOR_YEELOW = 0x0000FFFF; //黄色
        public readonly uint[] ColorMap = new uint[] { 0xff, 0xff00, 0xff0000, 0xffff, 0xffff00, 0xff00ff, 0xffffff, 0x000000 };
        public void Run()
        {
            this.httpListener.Prefixes.Add(string.Format("http://+:{0}/", this.port));
            this.httpListener.Start();
            this.httpListener.BeginGetContext(new AsyncCallback(GetContext),  this.httpListener);
            Console.WriteLine("Listen Port:" + port);

            JObject jsonObj = new JObject();
            jsonObj.Add("type", "ServerStarted");
           
            SendMsg(jsonObj);
        }
        public bool IsListening()
        {
            return httpListener.IsListening;
        }
       
        private void GetContext(IAsyncResult ar)
        {
            HttpListener httpListener = ar.AsyncState as HttpListener;
            HttpListenerContext context = httpListener.EndGetContext(ar);  //接收到的请求context（一个环境封装体）

            httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);  //开始 第二次 异步接收request请求

            HttpListenerRequest request = context.Request;  //接收的request数据
            HttpListenerResponse response = context.Response;  //用来向客户端发送回复

            string rawData;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                rawData = reader.ReadToEnd();
            }
            
            string type = request.QueryString["type"];//in/out,有车牌识别传入，判断进出场
            if (!string.IsNullOrEmpty(type))
            {
                try
                {
                    JObject jsonObj = JObject.Parse(rawData);
                    int sbcode;//摄像头进出场语音播报值
                    String cameraIP = (String)jsonObj["AlarmInfoPlate"]["ipaddr"];
                    String carno = (String)jsonObj["AlarmInfoPlate"]["result"]["PlateResult"]["license"];

                    Console.WriteLine("车牌号:" + carno);

                    JObject resultObj = new JObject();
                    resultObj.Add("type", "GetCarNo");
                    JObject resultDetailObj = new JObject();
                    resultDetailObj.Add("carNo", carno);
                    resultDetailObj.Add("inOut", type);
                    resultObj.Add("detail", resultDetailObj);

                    SendMsg(resultObj);

                    //服务器验证是否通行
                    try
                    {
                        String gateCode = App.GetBaseInfo().gateCode;
                        String[] gatecodes = gateCode.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        String ip = App.GetBaseInfo().HttpServerIp;
                        String port = App.GetBaseInfo().HttpServerPort;
                        JArray jArray = new JArray();
                        for (int i = 0; i < gatecodes.Length; i++)
                        {
                            JObject bodyJson = new JObject();
                            bodyJson.Add("type", type);//进出场
                            bodyJson.Add("carNo", carno);//车牌号
                            //bodyJson.Add("gateCode", gateCode);
                            bodyJson.Add("gateCode", gatecodes[i]);
                            jArray.Add(bodyJson);
                        }
                        JObject newJson = new JObject();
                        newJson.Add("jsonList", jArray);
                        //String bodyJsonStr = "{\"gateCode\":\"" + gateCode + "\", \"carNo\":\"" + carno + "\", \"type\":\"" + type + "\"}";

                        String result = HttpPostHelper.doHttpPost("http://"+ ip + ":"+ port + "/qd-s-factory/access/carApproachs", newJson.ToString());//改变车辆进场状态
                        JObject resJSON = JObject.Parse(result);
                        string status = (string)resJSON.GetValue("code");
                        string message = (string)resJSON.GetValue("message");
                       
                        if ("00000".Equals(status))
                        {
                            JObject checkResultObj = new JObject();
                            checkResultObj.Add("type", "Check");
                            checkResultObj.Add("inOut", type);
                            checkResultObj.Add("result", true);
                            checkResultObj.Add("message", "");
                            TcpRequestUtil.Main(type);
                            SendMsg(checkResultObj);

                            VzClientSDK.TEXT_CONTEXT[] TtextContext = new VzClientSDK.TEXT_CONTEXT[4]; //有几行就NEW几个结构体

                            TtextContext[0].LID = 0;
                            TtextContext[0].TextColor = 100;
                            TtextContext[0].Text = "出入平安";
                            /*第二行内容*/
                            TtextContext[1].LID = 1;
                            TtextContext[1].TextColor = 100;
                            TtextContext[1].Text = "识别成功";
                            /*第三行内容*/
                            TtextContext[2].LID = 2;
                            TtextContext[2].TextColor = 100;
                            TtextContext[2].Text = carno;
                            /*第四行内容*/
                            TtextContext[3].LID = 3;
                            TtextContext[3].TextColor = 100;
                            TtextContext[3].Text = "请通行";


                            int showTime = Int32.Parse("100");
                            if (showTime > 255)
                            {
                                showTime = 10;//展示时间
                            }
                            
                     
                            if ("out" == type)
                            {
                                 yy =  carno + ",出场";
                                 sbcode = handleOUT;
                            }
                            else {
                                yy =   carno + ",请入场";
                                 sbcode = handleIN;
                            }
                           
                            VzClientSDK.LED_MuiltLineDisAndPlayVoice(ref TtextContext, yy, 0, (byte)showTime, sbcode);
                            VzClientSDK.LED_OpenRelay((byte)showTime);


                            //  TcpRequestUtil.Main("in");//抬杆
                            // TcpRequestUtil.Main("out");



                            //JObject json = new JObject();
                            //sendScreen(json);

                            //String comm = App.GetBaseInfo().IO_Com_PortName;
                            //抬杆
                            //if ("in".Equals(type))
                            //{
                            //    TcpRequestUtil.Main("in");
                            //    //String inOpenPort = App.GetBaseInfo().IO_In_Open_Port;
                            //    //PortControlHelper.openDoor(comm, int.Parse(inOpenPort));
                            //}
                            //else if ("out".Equals(type))
                            //{
                            //    TcpRequestUtil.Main("out");
                            //    // PortControlHelper.openDoor(comm, int.Parse(outOpenPort));

                            //    //String outOpenPort = App.GetBaseInfo().IO_Out_Open_Port;
                            //    // PortControlHelper.openDoor(comm, int.Parse(outOpenPort));
                            //}
                        }
                        else
                        {
                            JObject checkResultObj = new JObject();
                            checkResultObj.Add("type", "Check");
                            checkResultObj.Add("inOut", type);
                            checkResultObj.Add("result", false);
                            checkResultObj.Add("message", message);
                            SendMsg(checkResultObj);
                            VzClientSDK.TEXT_CONTEXT[] TtextContext = new VzClientSDK.TEXT_CONTEXT[4]; //有几行就NEW几个结构体

                            TtextContext[0].LID = 0;
                            TtextContext[0].TextColor = 100;
                            TtextContext[0].Text = "出入平安";
                            /*第二行内容*/
                            TtextContext[1].LID = 1;
                            TtextContext[1].TextColor = 100;
                            TtextContext[1].Text = "识别成功";
                            /*第三行内容*/
                            TtextContext[2].LID = 2;
                            TtextContext[2].TextColor = 100;
                            TtextContext[2].Text = carno;
                            /*第四行内容*/
                            TtextContext[3].LID = 3;
                            TtextContext[3].TextColor = 100;
                           // TtextContext[3].Text = "临时车";


                            int showTime = Int32.Parse("100");
                            if (showTime > 255)
                            {
                                showTime = 10;
                            }


                            if ("out" == type)
                            {
                                TtextContext[3].Text = "禁止出场";
                                yy =   carno + ",禁止出场";
                                sbcode = handleOUT;
                            }
                            else
                            {
                                TtextContext[3].Text = "禁止入场";
                              //  TtextContext[3].Text = "临时车";
                                yy =  carno + ",禁止入场";
                                sbcode = handleIN;
                            }
                            
                            VzClientSDK.LED_MuiltLineDisAndPlayVoice(ref TtextContext, yy, 0, (byte)showTime, sbcode);
                            VzClientSDK.LED_OpenRelay((byte)showTime);
                        }
                    }
                    catch (Exception ex)
                    {
                        JObject checkResultObj = new JObject();
                        checkResultObj.Add("type", "Check");
                        checkResultObj.Add("inOut", type);
                        checkResultObj.Add("result", false);
                        checkResultObj.Add("message", ex.ToString());
                        
                        LogObject.WriteLog(ex.ToString(), "Message");
                        SendMsg(checkResultObj);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.GetBaseException());
                }
            }


            using (Stream output = response.OutputStream)  //发送回复
            {
                byte[] buffer = Encoding.UTF8.GetBytes("ok");
                output.Write(buffer, 0, buffer.Length);
            }
        }
        public struct TEXT_CONTEXT
        {
            public byte LID;   //显示行号
            public uint TextColor;//文本颜色
            public string Text;//显示文本
        };
        public void SendMsg(JObject obj)
        {
            if(sendMsgEvent != null)
            {
                sendMsgEvent(obj);
            }
        }
      
        private void DGOutList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }


        //public void sendScreen(JObject obj)
        //{
        //    if (sendVideoEvent != null)
        //    {
        //        sendVideoEvent(obj);
        //    }
        //}
    }
}
